from pymongo import MongoClient
from bson import ObjectId
client = MongoClient(host="mongodb://127.0.0.1",port=27017)
db = client['my_test']['gender']
'''练习1'''
# data = db.insert({'username':'sunwukong'})
# data = db.insert({'username':'zhubajei'})
# data_2 = db.find({})
# for i in data_2:
#     print(i)
# data_3 = db.remove({'username':'zhubajei'})  #删除全部的zhubajei
# data_4 = db.update({'username':'sunwukong'},{'$set':{'address':'huaguoshan'}})
# data_5 = db.update({'username':'zhubajei'},{'$set':{'username':'tangsen'}})
# data_6 = db.update({'username':'sunwukong'},{'$unset':{'address':'huaguoshan'}})
# data_7 = db.update({'username':'sunwukong'},{'$set':{'hobby':{'cities':['beijing','shanghai','shenzhen'],'movies':['sanguo','hero']}}})
# data_8 = db.update({'username':'tangsen'},{'$set':{'hobby':{'movies':['china','king']}}})

# data_9 = db.find({'hobby.movies':'hero'})
# print(list(data_9))

# data_10 = db.update_one({'username':'tangsen'},{'$push':{'hobby.movies':'interesting'}})

# data_11 = db.delete_one({'hobby.cities':'beijing'})

# data_12 = db.drop()

'''练习2'''
# mess = [{'num': i} for i in range(20000)]
# data_1 = db.insert_many(mess)
# data_2 = db.find({'num':500})
# print(list(data_2))

# data_3 = db.find({'num':{'$gt':5000}})
# for i in data_3:
#     print(i)

# data_3 = db.find({'num':{'$lt':30}})
# for i in data_3:
#     print(i)

# data_3 = db.find({'num':{'$lt':50,'$gt':40}})
# for i in data_3:
#     print(i)

# data_3 = db.find({'num':{'$gt':19996}})
# for i in data_3:
#     print(i)

# data_3 = db.find({}).limit(10)
# for i in data_3:
#     print(i)

# data_3 = db.find({}).limit(10).skip(11)
# for i in data_3:
#     print(i)

'''练习3'''
# client = MongoClient(host="mongodb://127.0.0.1",port=27017)
# db = client['eshop']['users']
# data = db.find_one({"_id" : ObjectId("5f017c5947ee089f7ff75e31")})['password']
# print(data)

'''练习4'''
# data = db.aggregate([{
#     '$group':{'_id':'$gender','number':{'$sum':1}}
# }])
# for i in data:
#     print(i)


data = db.aggregate([{
    '$match':{'age':{'$gt':20}}},
    {'$group':{'_id':'$gender','country':{'$sum':1}}},
     {'$project':{'_id':0,'gender':'$_id','country':1}}])
for i in data:
    print(i)



